package account;

import java.time.Instant;
import java.util.Random;

import aimee.common.MD5;
import aimee.common.RegexUtils;

/**
 * 密码类
 * 
 * @author 毛建杰
 *
 */
public class Password
{
	private String password;
	private int level;
	private String salt;

	/**
	 * 构造方法
	 * 
	 * @param password
	 *            密码
	 */
	public Password(String password)
	{
		this.level = passwordLevel(password);
		this.salt = MD5.encrypt(String.valueOf(Instant.now().toEpochMilli()) + new Random().nextInt(999)).substring(0,
				6);
		this.password = MD5.encrypt(MD5.encrypt(password) + salt);

		// 密码长度不满32位，左侧补0
		while (this.password.length() < 32)
		{
			this.password = "0" + this.password;
		}
	}

	/**
	 * 获取密码
	 * 
	 * @return 密码
	 */
	public String getPassword()
	{
		return password;
	}

	/**
	 * 获取密码安全等级
	 * 
	 * @return 密码安全等级
	 */
	public int getLevel()
	{
		return level;
	}

	/**
	 * 获取salt
	 * 
	 * @return salt
	 */
	public String getSalt()
	{
		return salt;
	}

	/**
	 * 计算密码安全等级
	 * 
	 * @param password
	 *            密码
	 * @return 安全等级
	 */
	public static int passwordLevel(String password)
	{
		int passwordLevel = 0;
		if (password.length() == 0)
		{
			passwordLevel = 0;
		}
		if (RegexUtils.matches(password, ".*[a-z]+.*") && RegexUtils.matches(password, ".*[0-9]+.*"))
		{
			passwordLevel += 1;
		}
		if (RegexUtils.matches(password, ".*[!@#$%^*()]+.*"))
		{
			passwordLevel += 1;
		}
		if (password.length() >= 10)
		{
			passwordLevel += 1;
		}
		return passwordLevel;
	}
}
